package com.xavi.socketdecodemjpeg

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.dwy.decodemjpeg.ObjectUtil
import java.io.IOException
import java.net.Socket

class SplashActivity : AppCompatActivity() {

    private lateinit var tvState: TextView
    private var state = false
    private var socket: Socket? = null
    private var ip = ""
    private var port = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        //tvState = findViewById(R.id.tvState)

        findViewById<Button>(R.id.btnOpenVideo).setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
        }

        /*Thread {
            while (true) {
                if (socket == null) {
                    state = false
                    runOnUiThread {
                        tvState.text = "未连接"
                    }
                    try {
                        socket = Socket()
                        socket?.connect(InetSocketAddress(ip, port.toInt()), 6000)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                socket?.let {
                    if (sendMsg(it, byteArrayOf(0x00))) {
                        state = true
                        runOnUiThread {
                            tvState.text = "已连接"
                        }
                    } else {
                        state = false
                        runOnUiThread {
                            tvState.text = "未连接"
                        }
                        try {
                            socket = Socket()
                            socket?.connect(InetSocketAddress(ip, port.toInt()), 6000)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
                Thread.sleep(1000)
            }
        }.start()

        findViewById<Button>(R.id.btnConnect).setOnClickListener {
            if (state) {
                Toast.makeText(this, "已连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            ip = findViewById<TextView>(R.id.etIp).text.toString().replace(" ", "")
            port = findViewById<TextView>(R.id.etPort).text.toString().replace(" ", "")
            if (TextUtils.isEmpty(ip)) {
                Toast.makeText(this, "请输入IP", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (!ip.contains(".")) {
                Toast.makeText(this, "IP格式错误1", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val ipArr = ip.split(".")
            if (ipArr.size != 4) {
                Toast.makeText(this, "IP格式错误2", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            ipArr.forEach {
                if (TextUtils.isEmpty(it) || !TextUtils.isDigitsOnly(it) || it.toInt() < 0 || it.toInt() > 255) {
                    Toast.makeText(this, "IP格式错误3", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
            }
            if (TextUtils.isEmpty(port) || !TextUtils.isDigitsOnly(port) || port.toInt() < 0 || port.toInt() > 65535) {
                Toast.makeText(this, "端口格式错误", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            Thread {
                socket = Socket()
                if (sendMsg(socket!!, byteArrayOf(0x00))) {
                    state = true
                    runOnUiThread {
                        tvState.text = "已连接"
                    }
                } else {
                    try {
                        socket?.connect(InetSocketAddress(ip, port.toInt()), 6000)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }.start()
        }

        findViewById<Button>(R.id.btnDisConnect).setOnClickListener {
            if (!state) {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            socket?.close()
            socket = null
            Log.d(TAG, "socket:$socket,socket.close()")
        }

        findViewById<Button>(R.id.btnSendHex).setOnClickListener {
            if (!state || socket == null) {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val hex = findViewById<EditText>(R.id.etHex).text.toString().replace(" ", "")
            if (TextUtils.isEmpty(hex) || hex.length % 2 != 0) {
                Toast.makeText(this, "请输入完整的16进制数据", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (sendMsg(socket!!, ObjectUtil.parseHexStringToBytes(hex))) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.btnClearHex).setOnClickListener {
            findViewById<EditText>(R.id.etHex).setText("")
        }

        findViewById<Button>(R.id.btnSendString).setOnClickListener {
            if (!state || socket == null) {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val string = findViewById<EditText>(R.id.etString).text.toString().replace(" ", "")
            if (TextUtils.isEmpty(string)) {
                Toast.makeText(this, "请输入原始字符", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (sendMsg(socket!!, string.toByteArray())) {
                Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show()
                try {
                    socket = Socket()
                    socket?.connect(InetSocketAddress(ip, port.toInt()), 6000)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        findViewById<Button>(R.id.btnClearString).setOnClickListener {
            findViewById<EditText>(R.id.etString).setText("")
        }*/
    }

    companion object {

        private val TAG = SplashActivity::class.java.simpleName

        private fun sendMsg(soc: Socket, messageData: ByteArray): Boolean {
            try {
                if (!soc.isClosed && !soc.isOutputShutdown && soc.isConnected) {
                    val os = soc.getOutputStream()
                    os.write(messageData) //写入完整数据包
                    os.flush()
                    Log.e(TAG,"发送成功:${ObjectUtil.bytes2Hex(messageData)}")
                    return true
                } else {
                    return false
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return false
            }
        }

        private fun checkConnected(socket: Socket): Boolean {
            return try {
                socket.sendUrgentData(0xff)
                true
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        }
    }
}